package com.itheima.tlias.filter;


import com.alibaba.fastjson.JSONObject;
import com.itheima.tlias.pojo.Result;
import com.itheima.tlias.utils.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.imageio.spi.ServiceRegistry;
import java.io.IOException;
import java.util.Enumeration;

@Slf4j
@Component
@WebFilter(urlPatterns ="/*")
public class loginCheckFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;


        String url = req.getRequestURL().toString();
        log.info("url为:{}",url);



        if (url.contains("login")){
            log.info("登录操作,放行.....");
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }


        Enumeration<String> JWT = req.getHeaders("token");
        String jwt = JWT.nextElement();
        if (!StringUtils.hasLength(jwt)){
            log.info("请求头为空，未登录");
            Result not_login = Result.error("NOT_LOGIN");
            //转换为json格式的数据返回
            String s = JSONObject.toJSONString(not_login);
            resp.getWriter().write(s);
            return;
        }

        try {
            JwtUtils.parseJWT(jwt);
        }catch (Exception e ){
            e.printStackTrace();
            log.info("解析令牌失败，用户名或密码错误");
            Result ERROR = Result.error("NOT_LOGIN");
            //转换为json格式的数据返回
            String s = JSONObject.toJSONString(ERROR);
            resp.getWriter().write(s);
            return;
        }
        log.info("令牌合法，放行");
        filterChain.doFilter(servletRequest,servletResponse);

    }
}
